package com.moss.cloud.common.security.interceptor;

import com.moss.cloud.auth.api.utils.JwtAccessToken;
import com.moss.cloud.common.core.custom.CustomHttpHeaders;
import com.moss.cloud.common.core.exception.SystemErrorType;
import com.moss.cloud.common.core.utils.BooleanHandel;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class CustomFeignInterceptor implements HandlerInterceptor {
    private static final String FEIGN_USER_AGENT = "okhttp";
    private static final String USER_AGENT = "User-Agent";
    @SneakyThrows
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String userAgent = request.getHeader(USER_AGENT);
        if(StringUtils.isNotBlank(userAgent) && userAgent.startsWith(FEIGN_USER_AGENT)){
            String clientToken = request.getHeader(CustomHttpHeaders.FROM_INNER);
            String authorization = request.getHeader(HttpHeaders.AUTHORIZATION);
            log.info("客户端认证信息:{}", clientToken);
            log.info("用户认证信息:{}", authorization);
            BooleanHandel.trueThrow(StringUtils.isBlank(clientToken)).throwMessage(SystemErrorType.CLIENT_AUTH_EMPTY);
            // 如果存在用户认证信息直接交给权限验证器
            if(StringUtils.isNotBlank(authorization)){
                return Boolean.TRUE;
            }
            if(StringUtils.isBlank(authorization) && StringUtils.isNotBlank(clientToken)){
                return JwtAccessToken.invalidJwtAccessToken(clientToken);
            }
        }
        return true;
    }


}
